

from tokenize import TokenError
from fastapi import Depends, Request, status
from fastapi.responses import JSONResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
import jwt
from sqlalchemy.orm import Session
from database import get_db
from exceptions import NotSuperuserError, UserInactiveError, UserNotFoundError
from log_config import logger
from models import SysUser
from db_manage import user_manage as user_manager
from utils.jwt_utils import verify_token

security = HTTPBearer()



async def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db)
    ) -> SysUser:
    """获取当前认证用户"""
    token = credentials.credentials
    payload = verify_token(token, "access")
    
    if payload is None:
        raise TokenError()
    
    username = payload.get("sub")
    if username is None:
        raise TokenError()
    # db = SessionLocal()
    user = user_manager.get_user(token, db)
    if user is None:
        raise UserNotFoundError()
    
    # if not user.is_active:
    #     raise UserInactiveError()
    
    return user

async def get_current_active_user(current_user: SysUser = Depends(get_current_user)) -> SysUser:
    """获取当前活跃用户"""
    # if not current_user.is_active:
    #     raise UserInactiveError()
    return current_user

async def get_current_superuser(current_user: SysUser = Depends(get_current_user)) -> SysUser:
    """获取当前超级用户"""
    # if not current_user.is_superuser:
    #     raise NotSuperuserError()
    return current_user